import { h } from 'vue';

import { message, Modal } from 'ant-design-vue';
import { acceptHMRUpdate, defineStore } from 'pinia';

import {
  get1688ShopDetailApi,
  get1688ToDouyinProductDetail,
  getBrandList,
  getProductUpdateRule,
  publishCheck,
} from '#/api';
import { auto1688stor } from '#/store';
import { similarity } from '#/utils';

const jinyikeys: any = {
  款式: ['样式', '款式'],
  适合性别: ['性别', '适合性别'],
  适合年龄: ['年龄', '适合年龄'],
  适用场合: ['场合', '适用场合'],
  适用季节: ['季节', '适用季节'],
  适用人群: ['人群', '适用人群'],
  适用身高: ['身高', '适用身高'],
  适用体重: ['体重', '适用体重'],
  功效: ['功效', '功能', '作用'],
  身体护理部位: ['身体护理部位', '适用部位', '部位'],
  鞋面内里材质: ['内里材质', '鞋面内里材质'],
  面料材质: ['面料材质', '材质', '主面料成分'],
  使用方式: ['类型', '使用方式'],
  贮存条件: ['储存方式', '储存条件', '储藏方法'],
  适用肤质: ['肤质', '适用肤质'],
  净含量: ['净含量（规格）', '净含量'],
  植物品种: ['植物品种', '品种'],
  颜色分类: ['颜色分类', '颜色'],
  尺码: ['尺码', '尺寸'],
  产地: ['产地', '生产地'],
  保质期: ['保质期', '保质期限'],
  包装规格: ['包装规格', '规格'],
};
export function generateRandomString(length: number) {
  let result = '';
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

// 优先考虑的选项
// const priorityKeys: any = ['通用', '四季', '四季通用'];

interface stateType {
  selectShop: any[];
  selectGoods: any[];
  shopTabs: any[];
  nowSelectTab: any;
  nowSelectGood: any;
  lodingBool: boolean;
  ingetdeteail: boolean;
  tbId: null | number;
}
let outerKey: any = null;

export const in1688ToDoudianStore = defineStore('to-1688-doudian-data', {
  state: (): stateType => ({
    selectShop: [],
    selectGoods: [],
    shopTabs: [],
    nowSelectTab: '',
    nowSelectGood: '',
    lodingBool: false,
    ingetdeteail: false,
    tbId: null,
  }),

  actions: {
    setselectShop(data: any) {
      this.selectShop = data;
    },
    async setSelectData(data: any) {
      this.lodingBool = false;
      const auto1688storTres = auto1688stor();
      this.selectGoods = data.selectGoods;
      this.tbId = data.tbId || null;
      this.ingetdeteail = true;
      // 过滤出需要修改的数据
      this.shopTabs = auto1688storTres.auto1688.bindShopList
        ?.filter((item) => {
          return this.selectShop.includes(item.shopId) && item.pType === 2;
        })
        .map((res: any) => {
          res.productDetailList = this.selectGoods.map((item) => {
            return {
              goodsTitle: '',
              offerId: item,
              isSelect: false,
              shopId: res.shopId,
              isLodin: true,
              mainPicList: [],
            };
          });
          return res;
        }) as any[];

      this.nowSelectTab = this.shopTabs.map((item) => item.shopId)[0];
      const res: any = await this.getGoodsDetailList(
        this.selectGoods,
        this.shopTabs.map((item) => item.shopId),
        null,
        data.tbId,
      );
      if (!res) {
        this.shopTabs.forEach((item) => {
          item.productDetailList.forEach((itemser: any) => {
            itemser.isLodin = false;
            itemser.lodinerr = true;
          });
        });
        this.ingetdeteail = false;
        // message.error('获取商品详情失败');
      }

      // console.log('res12316545', res);
      this.shopTabs.forEach(async (item, index) => {
        // if (item.shopId === this.nowSelectTab) {
        const aliDetealis = res
          .filter((itemser: any) => item.shopId === itemser.shopId)
          .map(async (data: any) => {
            data.categoryIdsOps = data.categoryIds
              ? data.categoryIds.map((ters: any) => ters.name)
              : [];
            let getRule = {
              productSpecRule: {},
              titleLimitRule: {},
            };
            if (data.categoryId) {
              this.checkProductPublish(
                data.categoryId,
                data.goodsTitle,
                data.shopId,
              );
              getRule = await this.getProductUpdateRuleFn(
                data.categoryId,
                data.shopId,
              );
            }
            data.isEvaluateOpened = !!(data.isEvaluateOpened * 1);
            data.rule = getRule;
            data.specInfo.specValues = this.formatSpecInfo(
              data.specInfo.specValues,
              getRule,
            );

            data.specPricesV2 = this.setspecPricesV2(
              data.specPricesV2,
              data.specInfo.specValues,
            );
            data.priceget = '';
            const maxPrice = Math.max(
              ...data.specPricesV2.map((item: any) => item.supplyPrice),
            );
            const minPrice = Math.min(
              ...data.specPricesV2.map((item: any) => item.supplyPrice),
            );
            if (minPrice === maxPrice) {
              data.priceget = minPrice;
            }
            data.priceget = `${minPrice}~${maxPrice}`;
            data.propertyList = await this.formatPropertyList(data);
            return {
              ...data,
              isSelect: false,
              isLodin: false,
            };
          });
        aliDetealis &&
          Promise.all(aliDetealis).then((res) => {
            res && (this.shopTabs[index].productDetailList = res);
            this.ingetdeteail = false;
          });
      });
      // this.ingetdeteail = false;
    },
    // 预检查是否可以发布
    async checkProductPublish(id: any, goodsTitle: any, shopId: any) {
      if (outerKey) return;
      outerKey = setTimeout(() => {
        clearTimeout(outerKey);
        outerKey = null;
      }, 2000);
      if (!id) return;
      const getConterids = {
        categoryId: id,
        goodsTitle,
        shopId,
      };
      publishCheck(getConterids).then((res: any) => {
        if (res !== 'success') {
          Modal.warning({
            title: '提示',
            content: h('div', {
              innerHTML: res,
            }),
            centered: true,
            onOk(clear) {
              clear && clear();
            },
          });
        }
      });
    },
    formatSpecInfo(specValues: any[], rule: any) {
      if (rule?.productSpecRule?.supportPropertyDiy) {
        const foters = specValues.map((item: any, index: number) => {
          const itemAutoData = rule.productSpecRule.requiredSpecDetails.find(
            (n: any) => {
              return n.sellPropertyName === item.propertyName;
            },
          );
          const updata = {
            showSwachSkuImage: index === 0,
            showSkuImage: index === 0,
            sellPropertyName: item.propertyName,
            id: index + 1,
            islodin: false,
            valueDisplayStyle: 'text',
            values: (() => {
              const vueilse =
                item.values && item.values.length > 0
                  ? item.values
                  : [
                      {
                        valueId: '',
                        valueName: '',
                      },
                    ];

              return vueilse.map((capers: any) => {
                const getC = itemAutoData?.propertyValues?.find((item: any) => {
                  return capers.valueName === item.sellPropertyValueName;
                });
                if (getC) {
                  capers.valueId = getC.sellPropertyValueId;
                }
                if (itemAutoData && !getC) {
                  if (itemAutoData.supportDiy) {
                    itemAutoData.propertyValues.push({
                      sellPropertyValueId: capers.valueName,
                      sellPropertyValueName: capers.valueName,
                    });
                    capers.valueId = capers.valueName;
                  } else {
                    capers.in1688Name = capers.valueName;
                  }
                }
                capers.selectmeasureitem = '';
                capers.id = Math.random().toString(36).slice(2, 32);
                capers.help = null;
                capers.validateStatus = null;
                capers.remark = '';
                return capers;
              });
            })(),
          };
          updata.showSwachSkuImage = index === 0;
          updata.showSkuImage = index === 0;
          if (itemAutoData) {
            Object.assign(updata, itemAutoData);
          }

          return updata;
        });
        return foters;
      }

      const getList =
        rule?.productSpecRule?.requiredSpecDetails
          ?.map((item: any, index: number) => {
            // console.log('item', item);

            item.id = index + 1;
            item.islodin = false;
            item.values = specValues.find(
              (item1: any) => item1.propertyName === item.sellPropertyName,
            )?.values;
            if (!item.values || item.values.length === 0) {
              // item.deleteItem = true;
              if (!item.isRequired) {
                item.deleteItem = true;
              }
              item.values = [
                {
                  valueId: '',
                  valueName: '',
                },
              ];
            }
            item.values.forEach((capers: any) => {
              capers.selectmeasureitem = '';

              if (item.valueDisplayStyle === 'measure') {
                capers.selectmeasureitem = item.measureTemplates[0].templateId;
              }
              capers.id = Math.random().toString(36).slice(2, 32);
              capers.help = null;
              capers.validateStatus = null;

              capers.remark = '';
              capers.showPopover = false;
              const getIter = item.propertyValues.find(
                (item1: any) =>
                  item1.sellPropertyValueName === capers.valueName,
              );
              if (getIter) {
                capers.valueId = getIter.sellPropertyValueId;
              } else if (item.supportDiy) {
                // 可以diy
                capers.valueId = capers.valueName;
                capers.isDiy = true;
                item.propertyValues.push({
                  sellPropertyValueId: capers.valueName,
                  sellPropertyValueName: capers.valueName,
                });
              } else {
                // 这里找相似
                const maxXiangshidu = item.propertyValues
                  .map((item1: any) => {
                    item1.xianshidu = similarity(
                      item1.sellPropertyValueName,
                      capers.valueName,
                    );
                    return item1;
                  })
                  .sort((a: any, b: any) => b.xianshidu - a.xianshidu)[0];
                capers.valueId = maxXiangshidu.sellPropertyValueId;
                capers.in1688Name = capers.valueName;
                capers.valueName = maxXiangshidu.sellPropertyValueName;
              }
              if (item.isRequired) {
                switch (item.valueDisplayStyle) {
                  case 'cascader_multi_select': {
                    if (!capers.valueId) {
                      capers.help = `规格必填`;
                      capers.validateStatus = 'error';
                    }
                    break;
                  }

                  default: {
                    break;
                  }
                }
              }
            });

            if (item.valueDisplayStyle === 'measure') {
              item.measureTemplates.forEach((item1q: any) => {
                item1q.valueModules.forEach((item2q: any) => {
                  item2q.id = Math.random().toString(36).slice(2, 32);
                  item2q.help = null;
                  item2q.validateStatus = null;
                  item2q.remark = '';
                  item2q.value = '';
                  item2q.selectValue = item2q.units[0]?.unitId || '';
                });
              });
              item.values.forEach((item1: any) => {
                item1.measureTemplates = [...item.measureTemplates];
              });
            }
            return item;
          })
          .filter((item: any) => !item.deleteItem) || [];

      const outListSort: any = [];
      specValues.forEach((item: any) => {
        const getIter = getList.find((item1: any) => {
          if (item1.sellPropertyName === item.propertyName) {
            item1.isUse = true;
            return true;
          }
          return false;
        });
        if (getIter) {
          item.isUse = true;
          outListSort.push(getIter);
        } else {
          item.sellPropertyName = item.propertyName;
          item.islodin = false;
          item.valueDisplayStyle = 'text';
          item.values.forEach((capers: any) => {
            capers.id = Math.random().toString(36).slice(2, 32);
            capers.help = null;
            capers.validateStatus = null;
            capers.remark = '';
            capers.valueId = capers.valueName;
            capers.isDiy = true;
            capers.in1688Name = capers.valueName;
          });
        }
      });
      const useNew = getList.filter((item: any) => {
        return !item.isUse;
      });
      const useOld = specValues.filter((item: any) => {
        item.iserror = true;
        item.errtext = '根据抖店的规格标准化，该规格不支持使用，请重新选择规格';
        return !item.isUse;
      });
      // console.log('useNew', outListSort);
      // console.log('useOld', useOld);
      outListSort.push(...useNew, ...useOld);
      outListSort.forEach((item: any, index: number) => {
        item.showSwachSkuImage = index === 0;
        item.showSkuImage = index === 0;
      });
      return outListSort;
    },

    removeItemFunc(item: any) {
      const { shopId, offerId } = item;
      this.shopTabs = this.shopTabs.filter((item) => {
        if (item.shopId === shopId) {
          item.productDetailList = item.productDetailList.filter(
            (data: any) => {
              return data.offerId !== offerId;
            },
          );
        }
        return item.productDetailList.length;
      });
    },
    removeSelectProducts(data: any) {
      this.shopTabs = this.shopTabs.filter((item) => {
        if (item.shopId === this.nowSelectTab) {
          item.productDetailList = item.productDetailList.filter(
            (item: any) => {
              return !data.includes(item.offerId);
            },
          );
        }
        return item.productDetailList.length;
      });
    },
    removeTab(shopId: any) {
      this.shopTabs = this.shopTabs.filter((item) => {
        return item.shopId !== shopId;
      });
      const getsteyr = this.shopTabs.find(
        (idse) => idse.shopId === this.nowSelectTab,
      );
      if (!getsteyr) {
        this.nowSelectTab =
          this.shopTabs.length > 0 ? this.shopTabs[0].shopId : '';
      }
    },
    // 获取商品详情列表
    getGoodsDetailList(
      itemId: number[],
      shopId: number[],
      categoryId?: null | number[],
      tbId?: number,
    ) {
      return new Promise((resolve, reject) => {
        const upData: any = {
          offerIds: itemId,
          shopIds: shopId, // || nowData.shopId,
        };
        if (categoryId) {
          upData.categoryIds = categoryId;
        }
        if (tbId) {
          upData.tbId = tbId;
          delete upData.shopIds;
          delete upData.offerIds;
          get1688ShopDetailApi(upData)
            .then((res) => {
              resolve([res]);
            })
            .catch((error) => {
              reject(error);
            });
          return;
        }

        get1688ToDouyinProductDetail(upData)
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    setspecPricesV2(specPricesV2: any, specValues: any) {
      const indentNames: any[] = [];
      return specPricesV2.map((item: any) => {
        item.stockNum1688 = item.stockNum;

        item.sellProperties.forEach((item1: any) => {
          specValues.forEach((item2: any) => {
            if (item1.propertyName === item2.sellPropertyName) {
              if (!indentNames.includes(item1.propertyName)) {
                indentNames.push(item1.propertyName);
              }
              item2.values.forEach((item3: any) => {
                if (item3.valueName === item1.valueName) {
                  item1.remark = item3.remark;
                  item1.id = item3.id;
                }
              });
            }
          });
        });
        // console.log('indentNames', indentNames);
        const notItem = specValues.filter((item2: any) => {
          return !indentNames.includes(item2.sellPropertyName);
        });
        // console.log('notItem', notItem);
        if (notItem && notItem.length > 0) {
          notItem.forEach((item2: any) => {
            item.sellProperties.push(item2.values[0]);
          });
        }
        // console.log(
        //   '(item.supplyPrice / 100).toFixed(2)',
        //   (item.supplyPrice / 100).toFixed(2),
        // );
        // console.log('item.sellProperties11', item.sellProperties);
        // if (isNowIndengt && specValues.length > item.sellProperties.length) {
        //   // console.log('isNowIndengt', isNowIndengt);
        //   item.sellProperties.push(isNowIndengt.values[0]);
        // }
        // console.log('item.sellProperties222', item.sellProperties);
        return {
          ...item,
          // isDelete: true,
          supplyPrice: (item.supplyPrice / 100).toFixed(2),
          price: (item.price / 100).toFixed(2),
          status: true,
        };
      });
    },
    async getItemDetail(offerId: number[], categoryId?: number) {
      // console.log('offerId', offerId);
      this.ingetdeteail = true;
      let getNow = [];
      if (Array.isArray(offerId)) {
        getNow = this.shopTabs
          .find((item) => {
            return item.shopId === this.nowSelectTab;
          })
          ?.productDetailList?.filter((item: any) => {
            return offerId.includes(item.offerId);
          });
      }
      const shtyer = this.shopTabs
        .find((item) => {
          return item.shopId === this.nowSelectTab;
        })
        ?.productDetailList?.find((item: any) => {
          return item.offerId === offerId;
        });
      if (shtyer) {
        getNow = [shtyer];
      }
      // console.log('getNow', getNow);
      // return;
      if (getNow && getNow.length > 0) {
        getNow.forEach((items: any) => {
          items.isLodin = true;
        });

        // getNow.isLodin = true;
        const res: any = await this.getGoodsDetailList(
          Array.isArray(offerId) ? offerId : [offerId],
          [this.nowSelectTab],
          categoryId
            ? [categoryId]
            : [getNow.map((item: any) => item.categoryId)[0]],
        );
        this.ingetdeteail = false;
        if (!res) {
          getNow.forEach((items: any) => {
            items.isLodin = false;
          });
          return;
        }

        this.shopTabs.forEach((item) => {
          // if (item.shopId === this.nowSelectTab) {
          const getallpromis = item.productDetailList.map(async (data: any) => {
            let newData = res.find(
              (reter: any) =>
                data.offerId === reter.offerId && data.shopId === reter.shopId,
            );

            if (newData) {
              if (!newData.categoryId) {
                message.error('该商品没有分类，请先选择分类');
                newData.isLodin = false;
                return newData;
              }
              this.checkProductPublish(
                newData.categoryId,
                newData.goodsTitle,
                newData.shopId,
              );
              const getRule = await this.getProductUpdateRuleFn(
                newData.categoryId,
                data.shopId,
              );
              newData.isEvaluateOpened = !!(newData.isEvaluateOpened * 1);
              newData.rule = getRule;
              newData.specInfo.specValues = this.formatSpecInfo(
                newData.specInfo.specValues,
                getRule,
              );
              newData.specPricesV2 = this.setspecPricesV2(
                newData.specPricesV2,
                newData.specInfo.specValues,
              );
              newData.priceget = '';
              const maxPrice = Math.max(
                ...newData.specPricesV2.map((item: any) => item.supplyPrice),
              );
              const minPrice = Math.min(
                ...newData.specPricesV2.map((item: any) => item.supplyPrice),
              );
              if (minPrice === maxPrice) {
                newData.priceget = minPrice;
              }
              newData.priceget = `${minPrice}~${maxPrice}`;
              newData.propertyList = await this.formatPropertyList(newData);
              newData = {
                ...newData,
                isSelect: data.isSelect,
                isLodin: false,
                shortProductName: data.shortProductName,
              };
              newData.categoryIdsOps = newData.categoryIds
                ? newData.categoryIds.map((ters: any) => ters.name)
                : [];
            }
            return newData || data;
          });
          Promise.all(getallpromis).then((res) => {
            item.productDetailList = res;
          });
          // }
        });
      }
    },
    async formatPropertyList(data: any) {
      // console.log('attributesList', data.attributesList);
      // console.log('propertyList', data.propertyList);
      if (!data.categoryId) return [];

      const poterAll = data.propertyList.map(async (item: any) => {
        item.wangwangAccount = data.wangwangAccount;
        item.title = data.goodsTitle;
        if (item.propertyId === 1687) {
          item.options = await this.getBrandListFun(
            data.categoryId,
            item.options,
            data.shopId,
          );
          item.optionsValue = item.options[0].value;
        }

        if (
          (item.propertyId !== 1687 && item.type === 'select') ||
          item.type === 'text'
        ) {
          item.optionsValue = null;
        }
        if (item.type === 'multi_select') {
          item.optionsValue = [];
        }
        if (item.type === 'measure') {
          // console.log('item', item);
          item.measureTemplates.forEach((item3: any) => {
            item3.valueModules.forEach((item2: any) => {
              item2.unitId = item2.units[0]?.unitId;
              item2.unitName = item2.units[0]?.unitName;
              item2.value = '';
            });
          });
          item.optionsValue = '';
          item.openStatus = false;
        }
        if (item.type === 'date_time_range') {
          item.optionsValue = [];
        }
        if (item.type === 'multi_value_measure') {
          item.optionsValue = [
            {
              value: '',
              valueId: '',
            },
          ];
        }
        if (this.tbId) {
          this.remackData(item, data.goodsOptionsList);
          return item;
        }
        this.marckData(item, data.attributesList);

        return item;
      });
      const res = await Promise.all(poterAll);
      return res;
    },
    remackData(item: any, attributesList: any[]) {
      // console.log('item', attributesList, item);
      const findTab = attributesList.find((attr: any) => {
        return attr.propertyId === item.propertyId;
      });
      if (!findTab) return;
      switch (item.type) {
        case 'measure': {
          const getItemMaxrter = findTab.subList[0];
          const units =
            item.measureTemplates[0]?.valueModules[0]?.units || null;
          if (!units) return;
          units.forEach((unit: any) => {
            // console.log('unit', unit);
            if (getItemMaxrter.name.includes(unit.unitName)) {
              item.optionsValue = {
                value: getItemMaxrter.name.replace(unit.unitName, ''),
                unit: unit.unitId,
              };
            }
          });
          break;
        }
        case 'multi_select': {
          item.optionsValue = findTab.subList.map((aters: any) => {
            // const trers: any = {};
            if (aters.diy_type === 1) {
              const findIds = item.options.find(
                (item: any) => item.valueId === aters.value,
              );
              // console.log('findIds', item, findIds, aters);
              if (!findIds && item.diyType === 1) {
                item.options.push({
                  disabled: false,
                  diyType: 1,
                  name: aters.name,
                  value: aters.value || aters.name,
                  valueId: 0,
                });
              }
            }
            if (!aters.value) {
              return aters.name;
            }

            return `${aters.value}` || aters.name;
          });
          break;
        }
        case 'multi_value_measure': {
          const lyetr = findTab.subList.map((ater: any) => {
            const conters: any = ater.measureInfo.values[0].value;
            const util: any = ater.measureInfo.values[1].unitName;
            return {
              valueId: conters,
              value: ater.name.replace(conters, '').replace(util, ''),
            };
          });
          item.optionsValue = lyetr;
          break;
        }
        case 'select': {
          const getConter = findTab.subList[0];
          if (getConter.diy_type === 1) {
            const findIds = item.options.find(
              (item: any) => item.valueId === getConter.value,
            );
            if (!findIds && item.diyType === 1) {
              item.options.push({
                disabled: false,
                diyType: 1,
                name: getConter.name,
                value: getConter.value || getConter.name,
                valueId: getConter.value || 0,
              });
            }
          }
          if (!getConter.value) {
            item.optionsValue = getConter.name;
            return;
          }
          item.optionsValue =
            item.propertyId === 1687
              ? getConter.value
              : `${getConter.value}` || getConter.name;
          break;
        }
        case 'text': {
          item.optionsValue = findTab.subList[0]?.name;
          break;
        }
        default: {
          break;
        }
      }
    },
    marckData(item: any, attributesList: any[]) {
      const copyList = [...attributesList];
      if (item.required === 1) {
        const retser = copyList
          .map((attr: any) => {
            // 查找近义词表 匹配最接近
            if (jinyikeys[item.propertyName]) {
              attr.xiangshidu = jinyikeys[item.propertyName]
                .map((item: any) => {
                  return similarity(attr.propertyName, item);
                })
                .sort((a: any, b: any) => b - a)[0];
              return attr;
            }
            attr.xiangshidu = similarity(attr.propertyName, item.propertyName);
            return attr;
          })
          .sort((a: any, b: any) => {
            return b.xiangshidu - a.xiangshidu;
          })
          .filter((a: any) => a.xiangshidu > 0.5);

        // console.log('retser', retser);
        if (retser.length === 0) {
          this.swatchData(item, attributesList);
          return;
        }
        this.swatchUseHot(item, retser);
      }
    },
    swatchUseHot(item: any, retser: any[]) {
      // 先查找是否有相识的选项 没有就默认第一个
      const getItemMaxrter = retser[0];

      switch (item.type) {
        case 'measure': {
          if (item.measureTemplates[0]?.valueModules.length > 1) return;
          const units =
            item.measureTemplates[0]?.valueModules[0]?.units || null;
          if (!units) return;
          units.forEach((unit: any) => {
            // console.log('unit', unit);
            if (getItemMaxrter.valueName.includes(unit.unitName)) {
              item.measureTemplates[0].valueModules[0].unitId = unit.unitId;
              item.measureTemplates[0].valueModules[0].unitName = unit.unitName;
              item.measureTemplates[0].valueModules[0].value =
                getItemMaxrter.valueName.replaceAll(/\D/g, '');
              item.optionsValue =
                getItemMaxrter.valueName.replaceAll(/\D/g, '') + unit.unitName;
            }
          });
          break;
        }
        case 'multi_select': {
          // 先判断是否包含
          const optionsnaem = [...item.options].find((optins) => {
            return getItemMaxrter.valueName.includes(optins.name);
          });
          if (optionsnaem) {
            item.optionsValue = [optionsnaem.value];
            return;
          }
          if (item.diyType === 1) {
            item.options.push({
              disabled: false,
              diyType: 1,
              name: getItemMaxrter.valueName,
              value: getItemMaxrter.valueName,
              valueId: 0,
            });
            item.optionsValue = [getItemMaxrter.valueName];
            return;
          }
          // 判断options
          const mareturn = [...item.options]
            .map((attrs: any) => {
              attrs.xiangshidu = similarity(
                attrs.name,
                getItemMaxrter.valueName,
              );
              return attrs;
            })
            .sort((a: any, b: any) => {
              return b.xiangshidu - a.xiangshidu;
            })
            .find((a) => a.xiangshidu >= 0.5);
          // 有 相似度 最大的 选中
          if (mareturn) {
            item.optionsValue = [mareturn.value];
            return;
          }
          // 没有 是不是可以diy    // 可以新建
          if (item.diyType === 1) {
            item.options.push({
              disabled: false,
              diyType: 1,
              name: getItemMaxrter.valueName,
              value: getItemMaxrter.valueName,
              valueId: 0,
            });
            item.optionsValue = [getItemMaxrter.valueName];
            return;
          }

          // 不行 默认第一个
          const getconters = item.options.find(
            (item: any) => item.name === 'PU',
          );
          item.optionsValue = getconters
            ? [getconters.value]
            : [item.options[0].value];

          break;
        }
        case 'multi_value_measure': {
          // console.log('getItemMaxrter++**--///*-', getItemMaxrter, retser);
          item.optionsValue = getItemMaxrter
            ? [
                {
                  value: 100,
                  valueId: getItemMaxrter.valueName,
                },
              ]
            : [
                {
                  value: 100,
                  valueId: '腈纶',
                },
              ];
          break;
        }
        case 'select': {
          if (
            item.options.length === 2 &&
            item.options[0].name === '是' &&
            item.options[1].name === '否'
          ) {
            item.optionsValue = item.options[1].value;
            return;
          }
          const getconterscd = item.options.find(
            (item: any) => item.name === '中国大陆',
          );
          if (getconterscd) {
            item.optionsValue = getconterscd.value;
            return;
          }
          if (item.propertyId === 1687) {
            return;
          }
          const getmaxOptionsReter = item.options
            .map((uter: any) => {
              uter.xiangshidu = similarity(uter.name, getItemMaxrter.valueName);
              return uter;
            })
            .filter((a: any) => a.xiangshidu >= 0.5)
            .sort((a: any, b: any) => {
              return b.xiangshidu - a.xiangshidu;
            })[0];
          if (getmaxOptionsReter) {
            item.optionsValue = getmaxOptionsReter.value;
            return;
          }
          if (item.diyType === 1) {
            item.options.push({
              disabled: false,
              diyType: 1,
              name: getItemMaxrter.valueName,
              value: getItemMaxrter.valueName,
              valueId: 0,
            });
            item.optionsValue = getItemMaxrter.valueName;
            // console.log('  item.options', item.options);
            return;
          }
          const getconters = item.options.find(
            (item: any) => item.name === '通用',
          );
          if (getconters) {
            item.optionsValue = getconters.value;
            return;
          }
          item.optionsValue = item.options[0].value;

          break;
        }
        case 'text': {
          item.optionsValue = getItemMaxrter.valueName;
          break;
        }
      }

      // console.log('getmaxOptionsReter', getmaxOptionsReter);

      // item.optionsValue = item.options[0].value;

      // console.log('retser+-+-', retser);
    },
    swatchData(item: any, attributesList: any[]) {
      switch (item.type) {
        case 'measure': {
          // if(item.measureTemplates..length > 1)
          let key = '';
          item.measureTemplates.forEach((item2: any) => {
            if (item2.valueModules.length > 1) {
              item2.valueModules.forEach((item3: any) => {
                item3.value = item3.validateRule.min;
                key =
                  (item3.prefix || '') +
                  key +
                  item3.value +
                  item3.suffix +
                  (item3.units[0]?.unitName || '');
              });
            }
          });
          item.optionsValue = key;
          break;
        }

        case 'multi_select': {
          const keyList: any = [];
          [...item.options].forEach((attrs: any) => {
            const findKey = attributesList.find((item) => {
              // console.log('item.propertyName', item.valueName, attrs.name);
              return item.valueName.includes(attrs.name);
            });
            if (findKey) {
              // console.log('findKey000', findKey);
              keyList.push(attrs.value);
            }
            const getXiansghidumap = attributesList
              .map((attr: any) => {
                attr.xiangshidu = similarity(attr.valueName, attrs.name);
                return attr;
              })
              .sort((a: any, b: any) => {
                return b.xiangshidu - a.xiangshidu;
              })
              .filter((a: any) => a.xiangshidu > 0.5);
            // console.log('getXiansghidumap', getXiansghidumap);
            if (getXiansghidumap.length > 0) {
              keyList.push(attrs.value);
            }
          });
          if (!keyList || keyList.length === 0) {
            keyList.push(item.options[0].value);
          }
          item.optionsValue = [...new Set(keyList)];
          break;
        }
        case 'multi_value_measure': {
          // console.log('getItemMaxrter++**--///*-', getItemMaxrter, retser);
          item.optionsValue = [
            {
              value: 100,
              valueId: '腈纶',
            },
          ];
          break;
        }
        case 'select': {
          if (
            item.options.length === 2 &&
            item.options[0].name === '是' &&
            item.options[1].name === '否'
          ) {
            item.optionsValue = item.options[1].value;
            return;
          }
          const getconterscd = item.options.find(
            (item: any) => item.name === '中国大陆',
          );
          if (getconterscd) {
            item.optionsValue = getconterscd.value;
            return;
          }
          if (item.propertyId === 1687) {
            return;
          }
          let optionsnow = '';
          let intitleMaxContent = 0;
          [...item.options].forEach((attrs: any) => {
            const findKey = attributesList.find((item) => {
              // console.log('item.propertyName', item.valueName, attrs.name);
              return item.valueName.includes(attrs.name);
            });
            if (findKey) {
              // console.log('findKey000', findKey);
              // keyLists.push(attrs.value);
              optionsnow = attrs.value;
              return;
            }
            const getXiansghidumap = attributesList
              .map((attr: any) => {
                attr.xiangshidu = similarity(attr.valueName, attrs.name);
                return attr;
              })
              .sort((a: any, b: any) => {
                return b.xiangshidu - a.xiangshidu;
              })
              .find((a: any) => a.xiangshidu > 0.5);

            if (getXiansghidumap) {
              optionsnow = attrs.value;
            }
            // 查找标题中 关联最大的
            const guanlian = similarity(item.title, attrs.name);
            if (guanlian > intitleMaxContent) {
              intitleMaxContent = guanlian;
              optionsnow = attrs.value;
            }
          });
          if (optionsnow) {
            item.optionsValue = optionsnow;
            return;
          }
          const getconters = item.options.find(
            (item: any) => item.name === '通用',
          );
          if (getconters) {
            item.optionsValue = getconters.value;
            return;
          }
          item.optionsValue = item.options[0].value;
          break;
        }
        case 'text': {
          switch (item.propertyId) {
            case 1479: {
              item.optionsValue = item.title;
              break;
            }
            case 1493: {
              item.optionsValue = generateRandomString(9);
              break;
            }
            case 2685: {
              item.optionsValue = item.wangwangAccount || '无';
              break;
            }
          }
          if (!item.optionsValue) {
            item.optionsValue = '参考详情';
          }
          break;
        }
      }
    },
    async getBrandListFun(categoryId: number, option: any, shopId: string) {
      const getBrandListData = await getBrandList(categoryId, shopId);

      const options = [
        {
          name: '无品牌',
          value: 596_120_136,
        },
        ...option,
      ];
      options.push(
        ...(getBrandListData.brandList?.map((br: any) => {
          return {
            name: (() => {
              if (br.nameCn && br.nameEn) return `${br.nameEn}/${br.nameCn}`;
              if (br.nameCn) return br.nameCn;
              if (br.nameEn) return br.nameEn;
            })(),
            value: br.brandId,
          };
        }) || []),
      );

      return options;
    },
    async getProductUpdateRuleFn(categoryId: number, shopId: string) {
      const res = await getProductUpdateRule(categoryId, shopId);
      if (res && res.qualificationRule) {
        res.qualificationRule.forEach((item: any) => {
          item.fileList = [];
          item.previewVisible = false;
          item.previewImage = '';
          item.previewTitle = '';
        });
      }
      if (!res) return {};
      return res;
    },
  },
  getters: {},
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(in1688ToDoudianStore, hot));
}
